package com.cutthroatcreations.woodenrailway;

import java.util.ArrayList;
import android.support.v4.app.ListFragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class TrainListFragment extends ListFragment {

	private static final String TAG = "TrainList";
	private OnTrainSelectedListener trainSelectedListener;
	private OnBackListener onBackListener;
	public OnUpdateListener onUpdateListener;
	public String currentYear;
	public int index;
	ArrayList<Train> parsed = new ArrayList<Train>();
	ArrayList<Train> trains = new ArrayList<Train>();
	TrainListAdapter trainListAdapter;
	Train selectedTrain;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		if (getActivity().getIntent().getIntExtra("year", -1) > -1) {
			this.index = getActivity().getIntent().getIntExtra("year", 0);
		} else {
			this.index = WoodenApplication.getYearIndex();
		}
		currentYear = WoodenApplication.cYears[this.index];

		trains = this.getTrainsByYear(currentYear);

		trainListAdapter = new TrainListAdapter(getActivity(),
				TrainListFragment.this, trains);
		setListAdapter(trainListAdapter);
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		trainSelectedListener.onTrainSelected(trains.get(position).getID(),
				trainListAdapter);
		
	}

	@Override
	public void onResume() {
		super.onResume();
		onUpdateListener.updateTextView(this.index);
		trainListAdapter.notifyDataSetChanged();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		onBackListener.setTextView();
	}
	
	public ArrayList<Train> getTrainsByYear(String y) {
		if (y == "1992/1993")
			y = "1993";
		if (y == "All Items")
			return WoodenApplication.allTrains;
		for (Train train : WoodenApplication.allTrains) {

			for (Integer i : train.allYears) {

				if (i == Integer.parseInt(y)) {

					parsed.add(train);

				}
			}
		}
		return parsed;
	}

	public void searchIt(CharSequence cs) {
		trainListAdapter.getFilter().filter(cs);
	}

	public void setTrains(ArrayList<Train> t) {
		this.trains = t;
	}

	public interface OnTrainSelectedListener {
		public void onTrainSelected(int id, TrainListAdapter tla);
	}

	public interface OnBackListener {
		public void setTextView();
	}

	public interface OnUpdateListener {
		public void updateTextView(int index);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			onBackListener = (OnBackListener) activity;
			onUpdateListener = (OnUpdateListener) activity;
			trainSelectedListener = (OnTrainSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement Interface");
		}
	}

}
